package xj.interceptor;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheKit;

import xj.model.SysUser;
import xj.utils.L;

public class AdminAuthInterceptor implements Interceptor {

	/**
	 * 为了便于项目在未来方便支持集群与分布式，已不建议使用 session 存放数据，建议将 session 范畴数据存放在数据库中。 redis
	 */
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		HttpSession session = controller.getSession();
		Object obj = session.getAttribute("usinfo");
		if (obj == null) {
			controller.redirect("/");
		} else {
			SysUser sysUser = (SysUser) obj;
			Integer userid = sysUser.getInt("userid");
			String sessionId = session.getId();
			if (sessionId != null && sessionId.equals((String)CacheKit.get("usinfoCache", userid))) {
				controller.getSession().setMaxInactiveInterval(7200);
				inv.invoke();
			} else {
				L.info("用户账号:" + userid + "被强制挤下线,sessionId为:" + sessionId);
				session.removeAttribute("usinfo");
				controller.redirect("/");
			}
		}
	}

	/**
	 * 等价于 session.getId();
	 */
//	private String getRequestSessionId(HttpServletRequest request) {
//		Cookie[] cookies = request.getCookies();
//		for (Cookie cookie : cookies) {
//			if (cookie.getName() != null && cookie.getName().startsWith("JSESSIONID")) {
//				return cookie.getValue();
//			}
//		}
//		return null;
//	}
}
